using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace ConwayPLinq 
{    
    public class LifeParser
    {
	public static IBoard Parse(Stream input)
	{
	    Board board;

	    using (var reader = new StreamReader(input)) 
		{
		    var values = reader.ReadLine().Split(',');
		    var x = int.Parse(values[0]);
		    var y = int.Parse(values[1]);

		    board = new Board(x, y);

		    string line;
		    int row = 0;
		    while(!String.IsNullOrEmpty(line = reader.ReadLine()))
			{
			    board.SetRow(row++, ParseRow(line));
			}
		}

	    return board;
	}

	public static bool[] ParseRow(string line) {
	    var list = new List<bool>();
	    foreach(var c in line.ToCharArray())
		{
		    list.Add(c != ' ');
		}
	    return list.ToArray();
	}

	public class Board : IBoard 
	{
	    private int _width;
	    private int _height;
	    bool[,] _data;

	    public void SetRow(int rowIndex, bool[] row) {
		for(int j = 0; j < _height; ++j) 
		    {
			_data[j, rowIndex] = row[j];
		    }
	    }

	    public Board(int width, int height)
		{
		    _width = width;
		    _height = height;
		    _data = new bool[_width,_height];
		}

	    public int Height { 
		get { return _height; }
	    }

	    public int Width { 
		get { return _width; }
	    }

	    public bool GetCellState(int x, int y) {
		return _data[x,y];
	    }
	    
	    public bool SetCellState(int x, int y, bool value) {
		var current = _data[x,y];
		_data[x,y] = value;

		return current;
	    }
	}
    }
}